﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO.IsolatedStorage;
using System.Linq;

namespace Com.PhilChuang.Pmvp.Model.Services.Impl
{
	public class PersistentAppStateService : IPersistentAppStateService
	{
		private readonly IsolatedStorageSettings myState = IsolatedStorageSettings.ApplicationSettings;

		public PersistentAppStateService ()
		{
		}

		#region Implementation of IEnumerable
		public IEnumerator<KeyValuePair<string, object>> GetEnumerator ()
		{
			foreach (var kvp in myState)
			{
				yield return kvp;
			}
			yield break;
		}

		IEnumerator IEnumerable.GetEnumerator ()
		{ return GetEnumerator (); }
		#endregion

		#region Implementation of ICollection<KeyValuePair<string,object>>
		public void Add (KeyValuePair<string, object> item)
		{ myState.Add (item.Key, item.Value); }

		public void Clear ()
		{ myState.Clear (); }

		public bool Contains (KeyValuePair<string, object> item)
		{ return myState.Contains (item.Key); }

		public void CopyTo (KeyValuePair<string, object>[] array, int arrayIndex)
		{
			int i = -1;
			foreach (var kvp in myState)
			{
				i++;
				if (i < arrayIndex) continue;
				array[i] = kvp;
			}
		}

		public bool Remove (KeyValuePair<string, object> item)
		{ return myState.Remove (item.Key);}

		public int Count
		{ get { return myState.Count; } }

		public bool IsReadOnly
		{ get { return false; } }
		#endregion

		#region Implementation of IDictionary<string,object>
		public bool ContainsKey (string key)
		{ return myState.Contains (key); }

		public void Add (string key, object value)
		{ myState.Add (key, value); }

		public bool Remove (string key)
		{ return myState.Remove (key); }

		public bool TryGetValue (string key, out object value)
		{ return myState.TryGetValue (key, out value); }

		public object this [string key]
		{
			get { return myState[key]; }
			set { myState[key] = value; }
		}

		public ICollection<string> Keys
		{ get { return myState.Keys.Cast<String> ().ToList (); } }

		public ICollection<object> Values
		{ get { return myState.Values.Cast<Object> ().ToList (); } }
		#endregion

		public void Save ()
		{
			myState.Save ();
		}
	}
}
